// 引入接口文件
import { queryAllAddress, queryBuildingPic, queryestateList, houseTypeList, sumbit, buildingDetail, getHouseTypeDetail, update } from './premisesDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"
import AppBus from 'utils/bus'
// 初始默认状态
const defultState = {
  btnLoading:false,
  buildingPic: {},
  areaList: [],
  //楼栋标注
  premiseMarker: {
    current: {
      label: '当前楼栋',
      //默认为0,0
      marker: [0, 0]
    },
    others: [
      // {
      //   label: '4栋',
      //   marker: [20, 20]
      // }
    ]
  },
  //弹框的当前楼栋坐标
  currPremiseMarker: [],
  //开始
  currStart: [],
  //坐标弹框显示
  premiseMarkerVisible: false,
  buildInfo: {},//后端交互数据
  estateList: [],
  houseList: [],
  houseTypeDetail: {},
  disabled:false,
}

// 声明module
const tmpModule = {
  namespace: 'baseinfoModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history, location }) {

      history.listen(({ pathname, query }) => {
        let { actionType, productId } = query
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
          dispatch({ type: 'updateStore', payload: { actionType, productId } });
          dispatch({ type: 'getAreaList', payload: {} });
          if (actionType == 'check' || actionType == 'edit') {
            dispatch({ type: 'getBuildingDetail', payload: { productId } });
          }
        }
      })
    },
  },

  // 方法列表
  effects: {
    // 查询记录
    * updateModel({ payload }, { put, select }) {
      yield put({ type: 'updateStore', payload });
    },
    *getAreaList({ payload }, { put, call, select }) {
      console.log()
      try {
        const data = yield call(queryAllAddress, {})
        if (data.success) {
          let areaList = []
          let arr = [data.data[0]]
          let attr = [data.data[data.data.length-1]]
          data.data[0] = {
            label:"北京",
            value:"110100",
            children:arr
          }
          data.data[data.data.length-1]={
            label:"澳门",
            value:"820000",
            children:attr
          }
          //去掉第三级，
          areaList = makeAddress(data.data,2,false)
          yield put({ type: 'updateStore', payload: { areaList: areaList } });
        }
      } catch (e) {

      }
    },
    *getBuildingPic({ payload }, { put, call, select }) {
      try {
        const data = yield call(queryBuildingPic, payload)
        let buildingPic
        if (data.success) {
          console.log(data.data)
          buildingPic = data.data
        }
        yield put({ type: 'updateStore', payload: { buildingPic } });
      } catch (e) {

      }
    },
    *getEstateList({ payload }, { put, call, select }) {
      try {
        let tmpState = yield select(state => state[tmpModule.namespace])
        let { buildInfo } = tmpState
        const { resolve,typeGet } = payload;
        let params = {
          pageNo: 1,
          pageSize: 1000,
          ...payload
        }
        const data = yield call(queryestateList, params)
        let estateList = []
        let zone
        if (data.success) {
          estateList = data.rows
          if(typeGet==1){
            let estateName
            let zone
         
             estateList.map((item,idx)=>{
              if(item.productId==buildInfo.parentProductId){
                estateName =item.name
                zone = item.estateRegion
                console.log(item)
              }
            })
            //debugger
            console.log(zone)
            yield put({ type: 'updateStore', payload: {zone} });
            yield put({
              type: 'getHouseTypeList',
              payload: { parentProductId: buildInfo.parentProductId,estateName}
            })
          }
          !!resolve && resolve(data.rows);
        }
        
        yield put({ type: 'updateStore', payload: { estateList} });
        
      } catch (e) {
      }

    },
    *getHouseTypeList({ payload }, { put, call, select }) {
      try {
        let params = {
          pageNo: 1,
          pageSize: 1000,
          ...payload
        }
        const data = yield call(houseTypeList, params)
        let houseList = []
        if (data.success) {
          houseList = data.rows
          yield put({ type: 'updateStore', payload: { houseList } });
        }

      } catch (e) {
      }
    },
    *sumbit({ payload }, { put, call, select }) {
      try {
        let tmpState = yield select(state => state[tmpModule.namespace])
        let { buildInfo } = tmpState
        if (tmpState.premiseMarker) {
          buildInfo.picx = tmpState.premiseMarker.current.marker[0]
          buildInfo.picy = tmpState.premiseMarker.current.marker[1]
        }
        if(buildInfo.openingTime==''){
          delete buildInfo.openingTime
        }
        yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
        if (tmpState.actionType == 'add') {
          const data = yield call(sumbit, buildInfo)
          yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
          console.log(data)
          if (data.success) {
            yield put({ type: 'updateStore', payload: { disabled:true } });
            message.success('提交成功').then(() => {
              let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
              AppBus.emit('closeTab', {
                key: urlArray[0],
                cbf: () => {
                  hashHistory.push(urlArray[1])
                }
              })
            });
          }
        } else {
          const data = yield call(update, buildInfo)
          yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
          if (data.success) {
            yield put({ type: 'updateStore', payload: { disabled:true } });
            message.success('编辑成功').then(() => {
              let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
              AppBus.emit('closeTab', {
                key: urlArray[0],
                cbf: () => {
                  hashHistory.push(urlArray[1])
                }
              })
            });
          }
        }
      } catch (e) {
        console.log(e)
      }
    },
    *getHouseTypeDetail({ payload }, { put, call, select }) {
      try {
        let tmpState = yield select(state => state[tmpModule.namespace])
        let { buildInfo } = tmpState
        const data = yield call(getHouseTypeDetail, payload)
        if (data.success) {
          //todo
          let houseTypeDetail = data.data
          yield put({
            type: 'updateStore',
            payload: { houseTypeDetail }
          })

        }
      } catch (e) {
        console.log(e)
      }
    },
    *getBuildingDetail({ payload }, { put, call, select }) {
      try {
        let tmpState = yield select(state => state[tmpModule.namespace])
        let { premiseMarker, } = tmpState
        const data = yield call(buildingDetail, payload)
        if (data.success) {
          let buildInfo = data.data
          premiseMarker.current.marker = [buildInfo.picx, buildInfo.picy]
          if(buildInfo.houseTypes){
             buildInfo.houseTypeIds = Object.keys(buildInfo.houseTypes)
          }
          yield put({ type: 'updateStore', payload: { buildInfo, premiseMarker } });
          yield put({ type: 'getBuildingPic', payload: { productId: buildInfo.parentProductId } })
          yield put({
            type: "getEstateList",
            payload: { province: buildInfo.province, city: buildInfo.city,typeGet:1 }//typeGet
          })
          
        }
      } catch (e) {
        console.log(e)
      }
    }
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
